import React, { FC, PropsWithChildren, useEffect, useState } from 'react';
import { type WSTYPE } from '@/utils/websocket/core';
import { createWebSocket } from '@/utils/websocket';
import { STORAGE } from '@/utils';
import EventUtil from '@/utils/event';
import { type CHAT_DETAIL_TYPE, type QUESTIONTYPE } from '@/request';
import { useSearchParams } from 'react-router-dom';
type CONTEXTTYPE = {
  ws: WSTYPE | null; // websocket实例
  sendMsg: (msg: SEND_MSG_TYPE) => void; // 发送websocket
  event: EventUtil; // 事件总线
  setChatDetail: React.Dispatch<React.SetStateAction<CHAT_DETAIL_TYPE | null>>;
  chatDetail: CHAT_DETAIL_TYPE | null; // 聊天详情
  stage: CHAT_DETAIL_TYPE['stage']; // 解题阶段
  setStage: React.Dispatch<React.SetStateAction<CHAT_DETAIL_TYPE['stage']>>;
  problem_id: string | null;
  questionDetail: QUESTIONTYPE['data'] | null;
  setQuestionDetail: React.Dispatch<
    React.SetStateAction<QUESTIONTYPE['data'] | null>
  >;
};

export const WrapContext = React.createContext<CONTEXTTYPE | null>(null);

export const Wrap: FC<PropsWithChildren> = (props) => {
  // 获取顶部参数problem_id
  const [URLSearchParams] = useSearchParams();
  const problem_id = URLSearchParams.get('problem_id');
  // websocket实例
  const [ws, setWs] = useState<WSTYPE | null>(null);
  // 聊天详情
  const [chatDetail, setChatDetail] = useState<CHAT_DETAIL_TYPE | null>(null);
  // 题目详情
  const [questionDetail, setQuestionDetail] = useState<
    QUESTIONTYPE['data'] | null
  >(null);
  // 解题阶段
  const [stage, setStage] = useState<CHAT_DETAIL_TYPE['stage']>('welcome');
  // 发送消息方法
  const sendMsg = (msg: SEND_MSG_TYPE) => {
    const _msg = JSON.stringify(msg);
    ws?.send(_msg);
  };
  // 事件实例化
  const event = new EventUtil();
  useEffect(() => {
    if (chatDetail?.id !== undefined) {
      const ws = createWebSocket({
        url: `${import.meta.env.VITE_APP_WS}/aitutor/chat/ws?cid=${chatDetail.id}&token=${sessionStorage.getItem(STORAGE.TOKEN)}`,
        isNeedHeart: false,
        onError(evt) {
          console.log(evt);
        },
        onClose() {
          console.log('close');
        },
        onLine() {
          console.log('online');
        },
        onOpen() {
          console.log('open');
        },
      });
      setWs(ws);
    }
  }, [chatDetail?.id]);
  return (
    <>
      <WrapContext.Provider
        value={{
          ws,
          sendMsg,
          event,
          setChatDetail,
          chatDetail,
          stage,
          setStage,
          problem_id,
          questionDetail,
          setQuestionDetail,
        }}>
        {props.children}
      </WrapContext.Provider>
    </>
  );
};
